export default class LayerManager {
    constructor(viewer) {
        this.viewer = viewer;
        this._layersList = [];
        this.geojsonData = {};
        this._imageryMap = new Array();
        this.init();
        this.Num = 0;
    }
    init() {
        this.viewer.scene.globe.showGroundAtmosphere = false; //关闭地面大气圈
        this.viewer.scene.skyAtmosphere.show = false; //关闭天空大气圈
       
    }
    addLayer(type, treeNode) {
        switch (type) {
            case 'pngxyz':
                let layerpngxyz = this.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                    url: treeNode.url,
                    tilingScheme: new Cesium.GeographicTilingScheme()
                }));
                this._imageryMap.push({
                    type: layerId,
                    layer: layerpngxyz
                });
                break;
            
            
            case 'geojson':
                Cesium.Math.setRandomNumberSeed(0); //设置随机数种子
                let promise = Cesium.GeoJsonDataSource.load(treeNode.url); //geojson面数据
                promise.then(function (dataSource) {
                    this.viewer.dataSources.add(dataSource);
                    // var entities = dataSource.entities.values;
                    // var colorHash = {};
                    // for (var i = 0; i < entities.length; i++) {
                    //     var entity = entities[i];
                    //     entity.polygon.material = Cesium.Color.red;
                    //     entity.polygon.strokeWidth = 10;
                    //     entity.polygon.outline = false;
                    // }
                });
                break;
            case 'img':
                let layerimg = this.viewer.imageryLayers.addImageryProvider(new Cesium.SingleTileImageryProvider({
                    url: treeNode.imgUrl,
                    rectangle: Cesium.Rectangle.fromDegrees(117.20, 31.33, 117.92, 31.82)
                }));
                this._imageryMap.push({
                    type: layerId,
                    layer: layerimg
                });
                break;
            case 'entity':
                let shareEntities = [];
                if (typeof (treeNode.flag) != 'undefined' && treeNode.flag == "ydyl") {
                    for (let i = 0; i < treeNode.billboards.length; i++) {
                        let label = new Cesium.LabelGraphics({
                            text: treeNode.billboards[i].text,
                            font: '20px Helvetica',
                            fillColor: Cesium.Color.BLANCHEDALMOND,
                            // outlineColor: Cesium.Color.block,
                            outlineColor: "#6E7018",
                            outlineWidth: 3,
                            pixelOffset: new Cesium.Cartesian2(0, -30),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE
                        });
                        let entity = this.viewer.entities.add({
                            id: layerId,
                            position: Cesium.Cartesian3.fromDegrees(treeNode.billboards[i].lon, treeNode.billboards[i].lat),
                            label: label,
                            billboard: {
                                image: treeNode.url
                            }
                        });
                        shareEntities.push(entity);
                    }
                } else {
                    for (let i = 0; i < treeNode.billboards.length; i++) {
                        let label = new Cesium.LabelGraphics({
                            text: treeNode.billboards[i].text,
                            font: '20px Helvetica',
                            fillColor: Cesium.Color.BLANCHEDALMOND,
                            // outlineColor: Cesium.Color.block,
                            outlineColor: "#6E7018",
                            outlineWidth: 3,
                            pixelOffset: new Cesium.Cartesian2(0, -30),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE
                        });
                        let entity = this.viewer.entities.add({
                            id: "entity" + i,
                            position: Cesium.Cartesian3.fromDegrees(treeNode.billboards[i].lon, treeNode.billboards[i].lat),
                            label: label,
                            billboard: {
                                image: treeNode.url
                            }
                        });
                        shareEntities.push(entity);
                    }
                }
                this._imageryMap.push({
                    type: layerId,
                    layer: shareEntities
                });
                break;
        }
    }
    removeLayer(item, layerId) {
        for (let i = 0; i < this._imageryMap.length; i++) {
            if (this._imageryMap[i].type == layerId) {
                if (item.type == "arcgis" || item.type == 'tms' || item.type == 'wms' || item.type == 'xyz' || item.type == 'pngxyz' || item.type == 'evia' || item.type == 'wmts') {
                    this.viewer.imageryLayers.remove(this._imageryMap[i].layer, true);
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "whiteModel" || item.type == 'geojson') {
                    if (this._imageryMap[i].layer) {
                        this._imageryMap[i].layer.destroy();
                    }
                    this.viewer.dataSources.removeAll();
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "video") {
                    this.viewer.entities.removeAll();
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "fineModel" || item.type == 'qingxieModel' || item.type == '3dTiles' || item.type == 'guomaoyinquAnalysis') {
                    this.viewer.scene.primitives.remove(this._imageryMap[i].layer)
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "landAnalysis") { }
                if (item.type == "diffAnalysis") { }
                if (item.type == "terrain") {
                    this.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({
                        ellipsoid: Cesium.Ellipsoid.WGS84
                    });
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == 'timeline') { }
                if (item.type == "juanlian") {

                    for (const layer of this._imageryMap[i].layer) {
                        this.viewer.imageryLayers.remove(layer, true);
                    }
                    this._imageryMap.splice(i, 1);
                    // item.handler.destroy();
                }
                if (item.type == 'poi') {
                    this.viewer.dataSources.remove(this._imageryMap[i].layer)
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == 'entity') {
                    // for (const entity of this._imageryMap[i].layer) {
                    //     this.viewer.entities.remove(entity);
                    // }
                    this.viewer.entities.removeAll();
                    this._imageryMap.splice(i, 1);
                }
            }
        }
    }
    addGeojson(url){
        Cesium.GeoJsonDataSource.load(url, {
            //clampToGround: false, //开启贴地
            stroke: Cesium.Color.fromCssColorString('rgba(115,227,230,1)'),
            strokeWidth: 3,
            fill: Cesium.Color.RED.withAlpha(.3)
        }).then(dataSource => {
            this.viewer.dataSources.add(dataSource)
            var geocacheEntities = dataSource.entities.values
            // for (var i = 0; i < geocacheEntities.length; i++) {
            //     var entity = geocacheEntities[i]
            //     //entity.polygon.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
            //     //entity.polygon.extrudedHeightReference= Cesium.HeightReference.CLAMP_TO_GROUND
            //     //entity.polygon.height = 1000
            //     entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN
            // }
            this.geojsonData[url] = dataSource
            console.log(this.geojsonData[url])
            this.viewer.flyTo(dataSource);
        })
    }
    removeGeojson(url) {
        if (url) {
            console.log()
            this.viewer.dataSources.remove(this.geojsonData[url])
            this.geojsonData[url] = null
        }
    }
    addBillboard(id,lon,lat,img){
        let entity = this.viewer.entities.add({
            id: id,
            position: Cesium.Cartesian3.fromDegrees(lon, lat),
            billboard: {
                image: img,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                //color : Cesium.Color.LIME, // default: WHITE
                width: 40,
                height: 40,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
        
    }
    removeBillboard(id){
        this.viewer.entities.removeById(id)
    }
    addPloygonLine(id, arr, color) {
        this.viewer.entities.add({
            id: id,
            polyline: {
                positions: Cesium.Cartesian3.fromDegreesArray(arr),
                clampToGround: true,
                width: 2,
                material: new Cesium.PolylineOutlineMaterialProperty({
                    color: color,
                    outlineWidth: 1,
                    outlineColor: Cesium.Color.BLACK,
                }),
            },
        });
    }
    getCenter(){
        let centerx = (this.viewer.camera.positionCartographic.longitude * 180) / Math.PI
        let centery = (this.viewer.camera.positionCartographic.latitude * 180) / Math.PI
        let height = Math.ceil(this.viewer.camera.positionCartographic.height)
        let heading = this.viewer.camera.heading
        let pitch = this.viewer.camera.pitch
        let roll = this.viewer.camera.roll
        return centerx + ',' + centery + ',' + height + ',' + heading + ',' + pitch + ',' + roll
    }
    fly( lon , lat , alt , heading , pitch , roll ) {
        this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(lon , lat , alt), // 设置位置
            orientation: {
                heading: heading, // 方向
                pitch: pitch, // 倾斜角度
                roll: roll
            },
        });
    }
    addDefaultLayer(val) {
        if (val.isactive) {
            switch (val.name) {
                case '全球影像':
                    let layerwms = this.viewer.imageryLayers.addImageryProvider(new GV.WebMapServiceImageryProvider({
                        url: "http://192.168.4.183:8310/geoserverplus/gwc/service/wms",
                        layers: "北京-PNG-4326",
                        parameters: {
                            format: 'image/png'
                        },
                        srs: 'EPSG:4326'
                    }));
                    this._layersList.push({
                        name: val.name,
                        layer: layerwms
                    })
                    break;
                case '全球地形':
                    break;
                case '全球海图':
                    let layerxyz = this.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                        url: "/layer/data/seamap/{z}/{x}/{y}.png"
                    }));
                    this._layersList.push({
                        name: val.name,
                        layer: layerxyz
                    })
                    break;
                case '全球矢量':
                    let layer = this.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                        url: "/layerdata/osm/{z}/{y}/{x}.png"
                    }));
                    this._layersList.push({
                        name: val.name,
                        layer: layer
                    })
                    break;
            }
        } else {
            this.removeDefaultLayer(val)
        }
        for (let item of this._layersList) {
            if (val.name !== item.name) {
                this.removeDefaultLayer(item)
            }
        }
    }
    removeDefaultLayer(item) {
        for (let i = 0; i < this._layersList.length; i++) {
            if (this._layersList[i].name == item.name) {
                this.viewer.imageryLayers.remove(this._layersList[i].layer, true);
                this._layersList.splice(i, 1);
            }
        }
    }
    removeAllLayer() {
        for (let i = 0; i < this._layersList.length; i++) {
            this.viewer.imageryLayers.remove(this._layersList[i].layer, true);
        }
        this._layersList = [];
    }
    cleanLayer() {
        for (let i = 0; i < this._imageryMap.length; i++) {
            if (this._imageryMap[i].layer instanceof Array) {
                // for (const entity of this._imageryMap[i].layer) {
                //     this.viewer.entities.remove(entity);
                // }
                this.viewer.entities.removeAll();
            } else {
                this.viewer.imageryLayers.remove(this._imageryMap[i].layer, true);
            }
        }
        this._imageryMap = [];
    }
    
}